/*******************************************************************************
 * Package: com.practice.config
 * Type:    SecurityConfiguration
 * Date:    2023/9/27 10:46
 *
 * Copyright (c) 2023 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.practice.config;

import com.alibaba.fastjson.JSON;
import com.practice.ex.ServiceErrorCode;
import com.practice.filter.JwtAuthorizationFilter;
import com.practice.web.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * TODO your comment
 *
 * @author Masiyu
 * @date 2023/9/27 10:46
 */
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 禁用“防止伪造的跨域攻击”这种防御机制
        http.csrf().disable();
        
        //登录页
        //http.formLogin();
        
        String[] urls = {
                "/doc.html",
                "/**/*.js",
                "/**/*.css",
                "/swagger-resources",
                "/v2/api-docs",
                "/user/login"
        };
    
        // 配置URL的访问控制
        http.authorizeRequests() // 配置URL的访问控制
                .mvcMatchers(urls) // 匹配某些URL
                .permitAll() // 直接许可，即：不需要通过认证就可以直接访问
                .anyRequest() // 任何请求
                .authenticated(); // 以上配置的请求需要是通过认证的
        
        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);
    
        // 处理“需要通过认证，但是实际上未通过认证就发起的请求”导致的错误
        http.exceptionHandling().authenticationEntryPoint((request, response, e) -> {
            String message = "未检测到登录，请登录！（在开发阶段，看到此提示时，请检查客户端是否携带了JWT向服务器端发起请求）";
            JsonResult<Void> jsonResult = new JsonResult(ServiceErrorCode.ERR_BAD_REQUEST.getCode(), message);
            response.setContentType("application/json; charset=utf-8");
            PrintWriter printWriter = response.getWriter();
            printWriter.println(JSON.toJSONString(jsonResult));
            printWriter.close();
        });
    }
    
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
